from flask import Blueprint, request, jsonify
from controllers.common import *
from controllers.db import *

store_event_project_api = Blueprint('store_event_project_api', __name__)
store_event_project_down_api = Blueprint('store_event_project_down_api', __name__)

@store_event_project_api.route('/store_event_project', methods=['POST'])
def store_event_project():
    params = json.loads(request.data)
    action = params['action']
    project = params['project']
    result_data = {'status': 200, 'data': {'msg': '', 'ret': 0, 'type': 'success', 'env': EVN, 'item': ''}}

    if action == 'detail':
        query = StoreEventProject.query.filter_by(project=project).first()
        tmp = {
            'project': int(query.project),
            'basic': json.loads(query.basic),
            'goal': json.loads(query.goal)
        }
        result_data['data']['item'] = tmp

    elif action == 'update_part':
        data = params['data']
        part = params['part']

        if part == 'basic':
            StoreEventProject.query.filter_by(project=project).update({
                'basic': json.dumps(data)
            })

        elif part == 'goal':
            project_data = StoreEventProject.query.filter_by(project=project).first()
            project_data.goal = json.dumps(data)

        db.session.commit()
        result_data['data']['msg'] = "更新成功"

    elif action == 'calendar_doc_id_list':
        calendar_doc_id_list = GetDocByFilenameNew('stockpile_event')
        return json.dumps(calendar_doc_id_list)
        # return json.dumps(GetNewOperationEventList('boss_incoming_event', 'title'))

    elif action == 'event_ui_list':
        with open(STATIC_PATH + 'bandit_event_project/event_ui_list.json', encoding='UTF-8') as f:
            data = json.load(f)
            result = []
            for i in data:
                result.append({
                    "value": i['value'],
                    "label": f"{i['value']} - {i['label']}"
                })
            return json.dumps(result)

    return jsonify(result_data)

@store_event_project_down_api.route("/store_event_project_down/<int:is_push>", methods=['POST', 'GET'])
def DownAction(is_push):
    result = {}
    query = StoreEventProject.query.order_by('project').all()
    for que in query:
        project = str(que.project)
        basic = json.loads(que.basic)
        goal = json.loads(que.goal)
        remark = que.remark

        doc_id = basic['doc_id']
        for node in goal:
            node['reward'] = RewardToTMysqlDuelYard(node['reward'], 'store')

        tmp = {
            'remark': remark,
            'basic': {
                'event_ui': basic['event_ui']
            },
            'localization_doc': {
                'title': doc_id,
                'info': doc_id,
                'content': doc_id
            },
            'goal': goal
        }
        result[project] = tmp

    response = DownLoad('store_event_project', result, is_push)

    return response
